#!/usr/bin/env python

#
# vcfsplitqp.py -- by Dario Berzano <dario.berzano@cern.ch>
#
# From an input VCF 2.1 with several entries, creates a separated VCF for each
# entry and converts "fancy" strings to Quoted-Printable.
#
# The output format is Nokia OVI Suite friendly.
#

import sys
import re
import quopri
import os

def main(infn, outdir, forceqp=False):
  """This is the main function. Two arguments: input file name and output
  directory. Output files will be overwritten.
  """

  # Creates dir first
  try:
    os.mkdir(outdir)
  except OSError:
    print "Cannot create directory (check that it does not exist yet)"
    return False

  recod = r'^(.*)(;CHARSET=[Uu][Tt][Ff]-8):(.*)$'
  renocod = r'^([^:]*):(.*)$'
  recomma = r'\\,'  # Apple Address Book incorrectly escapes commas :-/
  retel = r'^TEL;'
  vccount = 0
  outcount = 0
  incard = False
  hastel = False  # True if contact has at least one phone number

  with open(infn, "r") as f:
    for line in f:
      line = line.rstrip()

      if incard:

        if line == "END:VCARD":
          cardlines.append(line)
          incard = False
          vccount = vccount + 1
          # print("=== BEGIN #%u ===" % vccount)
          # print("%s" % cardlines)
          # print("Has telephone: %s" % hastel)
          # print("=== END #%u ===\n" % vccount)
          if hastel:
            outcount = outcount + 1
            try:
              of = open("%s/%04d.vcf" % (outdir,outcount), "w")
              for cl in cardlines:
                of.write("%s\r\n" % cl)
              of.close()
            except IOError as e:
              print "Error reading or writing: %s" % e
              return False

        else:
          line = re.sub(recomma, ',', line)  # unescape commas
          rem = None
          if forceqp:
            rem = re.match(renocod, line)
            if rem:
              cardlines.append("%s;ENCODING=QUOTED-PRINTABLE;CHARSET=utf-8:%s" % (
                rem.group(1),
                quopri.encodestring(rem.group(2)).replace('\\n', '=0A')
              ))
          else:
            rem = re.match(recod, line)
            if rem:
              #cardlines.append("%s;ENCODING=QUOTED-PRINTABLE;CHARSET=utf-8:%s" % (
              cardlines.append("%s;ENCODING=QUOTED-PRINTABLE%s:%s" % (
                rem.group(1),
                rem.group(2),
                quopri.encodestring(rem.group(3)).replace('\\n', '=0A')
              ))
              #print "{%s}-->{%s},{%s}" % (line.rstrip(),rem.group(2),quopri.encodestring(rem.group(3).rstrip()))

          if not rem:
            cardlines.append(line)
          if not hastel and re.match(retel, line):
            hastel = True

      elif line == "BEGIN:VCARD":
        cardlines = []
        cardlines.append(line)
        incard = True
        hastel = False

  return True

#
# Execute main() function when invoked as an executable
#

if __name__ == "__main__":
  if (len(sys.argv) < 3):
    print "Usage: %s [infile] [outdir] [--forceqp]" % (sys.argv[0])
  else:
    forceqp = False
    try:
      if sys.argv[3] == '--forceqp':
        forceqp = True
    except IndexError:
      pass
    main( sys.argv[1], sys.argv[2], forceqp )
